<template>
	<view class="page-activity-record">
		<!-- 页面标题栏 -->
		<view class="page-header">
			<view class="header-content">
				<text class="page-title">活动记录</text>
				<view class="history-btn" @tap="goToHistory">
					<u-icon name="clock" size="24" color="#666"></u-icon>
					<text class="history-text">历史记录</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-container" v-if="loading && activityRecords.length === 0">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 活动记录列表 -->
		<view class="activity-list" v-else>
			<!-- 空状态 -->
			<view class="empty-state" v-if="activityRecords.length === 0 && !loading">
				<text class="empty-text">暂无活动记录</text>
			</view>
			
			<view class="activity-card" v-for="(record, index) in activityRecords" :key="`record-${record.id}-${index}`">
				<!-- 卡片头部 -->
				<view class="card-header">
					<text class="activity-title">{{ record.title }}</text>
					<view class="status-tag" :class="record.statusClass">
						<text class="status-text">{{ record.status }}</text>
						<text class="time-text">{{ record.time }}</text>
					</view>
				</view>

				<!-- 活动信息 -->
				<view class="activity-info">
					<text class="info-text">老人姓名：{{ record.elderName }}</text>
					<text class="info-text">活动时间：{{ record.activityTime }}</text>
				</view>

				<!-- 活动描述 -->
				<view class="activity-description">
					<text class="description-text">活动描述：{{ record.description }}</text>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="action-btn primary" @tap="confirmMedication(record)">确认服药</button>
					<button class="action-btn secondary" @tap="showUploadModal(record)">上传图文</button>
					<button class="action-btn secondary" v-if="record.canDelay" @tap="delayReminder(record)">延后提醒</button>
				</view>
			</view>
			
			<!-- 加载更多提示 -->
			<view class="load-more-container" v-if="activityRecords.length > 0">
				<view class="load-more-tip" v-if="loadMoreStatus === 'loading'">
					<text class="load-more-text">加载中...</text>
				</view>
				<view class="load-more-tip" v-else-if="loadMoreStatus === 'noMore'">
					<text class="load-more-text">没有更多数据了</text>
				</view>
				<view class="load-more-tip" v-else-if="loadMoreStatus === 'more'">
					<text class="load-more-text">上拉加载更多</text>
				</view>
			</view>
		</view>

		<!-- 上传图文弹窗 -->
		<view class="upload-modal" v-if="showUploadModalFlag" @tap="closeUploadModal">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">上传图文</text>
					<view class="close-btn" @tap="closeUploadModal">
						<text class="close-icon">×</text>
					</view>
				</view>
				
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">活动名称</text>
						<input class="form-input" v-model="uploadForm.activityName" placeholder="喂药提醒" />
					</view>
					
					<view class="form-item">
						<text class="form-label">完成时间</text>
						<input class="form-input" v-model="uploadForm.completionTime" placeholder="2022-7-23 16:27:35" />
					</view>
					
					<view class="form-item">
						<text class="form-label">完成描述</text>
						<textarea class="form-textarea" v-model="uploadForm.description" placeholder="请输入备注信息" />
					</view>
					
					<view class="form-item">
						<text class="form-label">上传附件</text>
						<view class="attachment-area">
							<view class="attachment-item" v-for="(attachment, index) in uploadForm.attachments" :key="index">
								<image class="attachment-thumb" :src="attachment" mode="aspectFill" />
								<view class="remove-btn" @tap="removeAttachment(index)">
									<text class="remove-icon">×</text>
								</view>
							</view>
							<view class="add-attachment" @tap="addAttachment" v-if="uploadForm.attachments.length < 5">
								<text class="add-icon">+</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="modal-btn cancel" @tap="closeUploadModal">取消</button>
					<button class="modal-btn submit" @tap="submitUpload">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { apiGetActivityRecords } from '@/request/api.js'

export default {
	data() {
		return {
			showUploadModalFlag: false,
			uploadForm: {
				activityName: '',
				completionTime: '',
				description: '',
				attachments: []
			},
			activityRecords: [],
			// 分页参数
			pageInfo: {
				page: 1,
				limit: 10,
				total: 0
			},
			// 加载状态
			loading: false,
			loadMoreStatus: 'more', // more/loading/noMore
			// 用户信息
			memberId: 1 // 默认老人ID，实际应从用户选择或路径参数获取
		}
	},
	onLoad(options) {
		// 页面加载时的初始化
		if (options.member_id) {
			this.memberId = options.member_id;
		}
		// 加载活动记录
		this.loadActivityRecords();
	},
	
	// 页面下拉刷新
	onPullDownRefresh() {
		this.refreshData();
	},
	
	// 页面上拉触底
	onReachBottom() {
		this.loadMore();
	},
	methods: {
		// 加载活动记录
		async loadActivityRecords(isRefresh = false) {
			if (this.loading) return;
			
			this.loading = true;
			
			try {
				// 如果是刷新，重置页码
				if (isRefresh) {
					this.pageInfo.page = 1;
					this.activityRecords = [];
				}
				
				// 构建请求参数
				const data = {
					member_id: this.memberId,
					page: this.pageInfo.page,
					limit: this.pageInfo.limit
				};
				
				const response = await apiGetActivityRecords(data);
				
				if (response.code === 0) {
					const { data: records, count } = response;
					
					// 处理数据
					const processedRecords = this.processActivityRecords(records || []);
					
					if (isRefresh) {
						// 刷新时也确保去重
						this.activityRecords = this.removeDuplicateRecords(processedRecords);
					} else {
						// 合并数据时去重
						const mergedRecords = [...this.activityRecords, ...processedRecords];
						this.activityRecords = this.removeDuplicateRecords(mergedRecords);
					}
					
					this.pageInfo.total = count || 0;
					
					// 更新加载更多状态
					if (this.activityRecords.length >= this.pageInfo.total) {
						this.loadMoreStatus = 'noMore';
					} else {
						this.loadMoreStatus = 'more';
					}
				} else {
					uni.showToast({
						title: response.msg || '获取活动记录失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载活动记录失败:', error);
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				// 停止下拉刷新
				uni.stopPullDownRefresh();
			}
		},
		
		// 处理活动记录数据
		processActivityRecords(records) {
			// 先根据ID去重原始数据
			const uniqueRecords = this.removeDuplicateById(records);
			
			return uniqueRecords.map(record => {
				// 根据type确定活动类型
				const typeMap = {
					1: '娱乐活动',
					2: '用药提醒',
					3: '健康检查',
					4: '饮食管理'
				};
				
				// 处理时间显示
				const eventTime = record.event_time || record.create_time;
				const timeStr = this.formatTime(eventTime);
				
				// 根据时间和状态确定显示状态
				const status = this.getActivityStatus(record);
				
				return {
					id: record.id,
					title: record.title || typeMap[record.type] || '活动记录',
					status: status.text,
					time: timeStr,
					statusClass: status.class,
					elderName: record.name || '未知',
					activityTime: this.formatDateTime(eventTime),
					description: record.desc || record.num_desc || '暂无描述',
					canDelay: record.type === 2 && status.class !== 'completed',
					rawData: record // 保存原始数据
				};
			});
		},
		
		// 根据ID去重原始数据
		removeDuplicateById(records) {
			const seen = new Set();
			const duplicates = [];
			const unique = records.filter(record => {
				const id = record.id;
				if (seen.has(id)) {
					duplicates.push(id);
					return false;
				}
				seen.add(id);
				return true;
			});
			
			// 开发环境下打印去重信息
			if (duplicates.length > 0) {
				console.log('发现重复ID:', duplicates);
			}
			
			return unique;
		},
		
		// 去重处理后的活动记录
		removeDuplicateRecords(records) {
			const seen = new Set();
			const duplicates = [];
			const unique = records.filter(record => {
				const id = record.id;
				if (seen.has(id)) {
					duplicates.push(id);
					return false;
				}
				seen.add(id);
				return true;
			});
			
			// 开发环境下打印去重信息
			if (duplicates.length > 0) {
				console.log('去重处理后的记录中发现重复ID:', duplicates);
			}
			
			return unique;
		},
		
		// 获取活动状态
		getActivityStatus(record) {
			const now = new Date();
			const eventTime = new Date(record.event_time || record.create_time);
			
			// 如果有update_time说明已完成
			if (record.update_time && record.update_time !== '1970.01.01') {
				return { text: '已完成', class: 'completed' };
			}
			
			// 计算时间差（分钟）
			const diffMinutes = (now - eventTime) / (1000 * 60);
			
			if (diffMinutes > 30) {
				return { text: '即将逾期', class: 'urgent' };
			} else if (diffMinutes > 0) {
				return { text: '待处理', class: 'pending' };
			} else {
				return { text: '未到时间', class: 'scheduled' };
			}
		},
		
		// 格式化时间显示
		formatTime(timeStr) {
			if (!timeStr || timeStr === '1970.01.01') return '--:--';
			
			try {
				const date = new Date(timeStr);
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			} catch (e) {
				return '--:--';
			}
		},
		
		// 格式化完整日期时间
		formatDateTime(timeStr) {
			if (!timeStr || timeStr === '1970.01.01') return '暂无时间';
			
			try {
				const date = new Date(timeStr);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			} catch (e) {
				return '时间格式错误';
			}
		},
		
		// 刷新数据
		refreshData() {
			this.loadActivityRecords(true);
		},
		
		// 加载更多
		loadMore() {
			if (this.loadMoreStatus !== 'more' || this.loading) return;
			
			this.loadMoreStatus = 'loading';
			this.pageInfo.page += 1;
			this.loadActivityRecords();
		},
		
		// 跳转到历史记录
		goToHistory() {
			uni.navigateTo({
				url: `/pages/historyRecord/historyRecord?member_id=${this.memberId}`
			});
		},
		
		// 确认服药
		confirmMedication(record) {
			uni.showModal({
				title: '确认服药',
				content: `确认${record.elderName}已服药？`,
				success: (res) => {
					if (res.confirm) {
						uni.showToast({
							title: '已确认服药',
							icon: 'success'
						});
						// 这里可以调用API更新服药状态
					}
				}
			});
		},
		
		// 显示上传图文弹窗
		showUploadModal(record) {
			// 重置表单数据
			this.uploadForm = {
				activityName: record.title,
				completionTime: record.activityTime,
				description: '',
				attachments: []
			};
			this.showUploadModalFlag = true;
		},
		
		// 关闭上传图文弹窗
		closeUploadModal() {
			setTimeout(() => {
				this.showUploadModalFlag = false;
			}, 100);
		},
		
		// 添加附件
		addAttachment() {
			uni.chooseImage({
				count: 5 - this.uploadForm.attachments.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.uploadForm.attachments = this.uploadForm.attachments.concat(res.tempFilePaths);
				}
			});
		},
		
		// 移除附件
		removeAttachment(index) {
			this.uploadForm.attachments.splice(index, 1);
		},
		
		// 提交上传
		submitUpload() {
			// 验证表单数据
			if (!this.uploadForm.activityName.trim()) {
				uni.showToast({
					title: '请输入活动名称',
					icon: 'none'
				});
				return;
			}
			
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});
			
			// 重置表单并关闭弹窗
			this.uploadForm = {
				activityName: '',
				completionTime: '',
				description: '',
				attachments: []
			};
			this.closeUploadModal();
		},
		
		// 延后提醒
		delayReminder(record) {
			uni.showActionSheet({
				itemList: ['延后30分钟', '延后1小时', '延后2小时', '取消'],
				success: (res) => {
					if (res.tapIndex < 3) {
						const delayTimes = ['30分钟', '1小时', '2小时'];
						uni.showToast({
							title: `已延后${delayTimes[res.tapIndex]}`,
							icon: 'success'
						});
						// 这里可以调用API更新提醒时间
						record.status = '延后提醒';
						record.statusClass = 'delayed';
						record.canDelay = false;
					}
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.page-activity-record {
	min-height: 100vh;
	background: #F8F8F8;
}

.page-header {
	background: #FFFFFF;
	padding: 20rpx 30rpx 20rpx;
	margin-top: 60rpx;
	border-bottom: 1rpx solid #E5E5E5;
	position: relative;
}

.header-content {
	display: flex;
	justify-content: center;
	align-items: center;
	padding-top: 20rpx;
	position: relative;
}

.page-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.history-btn {
	display: flex;
	align-items: center;
	padding: 8rpx 12rpx;
	background: #F8F8F8;
	border-radius: 16rpx;
	position: absolute;
	right: 0;
}

.history-text {
	font-size: 22rpx;
	color: #666666;
	margin-left: 6rpx;
}

.activity-list {
	padding: 20rpx 16rpx;
}

.activity-card {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	border: 1rpx solid #F0F0F0;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.activity-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.status-tag {
	display: flex;
	align-items: center;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	gap: 8rpx;
}

.status-tag.urgent {
	background: #FFF2E6;
	border: 1rpx solid #FF7D00;
}

.status-tag.delayed {
	background: #E8F5E8;
	border: 1rpx solid #00C851;
}

.status-tag.pending {
	background: #F0F0F0;
	border: 1rpx solid #999999;
}

.status-tag.scheduled {
	background: #E3F2FD;
	border: 1rpx solid #2196F3;
}

.status-tag.completed {
	background: #E8F5E8;
	border: 1rpx solid #4CAF50;
}

.status-text {
	font-size: 22rpx;
	font-weight: 500;
}

.status-tag.urgent .status-text {
	color: #FF7D00;
}

.status-tag.delayed .status-text {
	color: #00C851;
}

.status-tag.pending .status-text {
	color: #999999;
}

.status-tag.scheduled .status-text {
	color: #2196F3;
}

.status-tag.completed .status-text {
	color: #4CAF50;
}

.time-text {
	background: #FF7D00;
	color: #FFFFFF;
	font-size: 20rpx;
	font-weight: bold;
	padding: 4rpx 12rpx;
	border-radius: 10rpx;
}

.status-tag.delayed .time-text {
	background: #00C851;
}

.status-tag.pending .time-text {
	background: #999999;
}

.status-tag.scheduled .time-text {
	background: #2196F3;
}

.status-tag.completed .time-text {
	background: #4CAF50;
}

.activity-info {
	margin-bottom: 20rpx;
}

.info-text {
	display: block;
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 8rpx;
}

.activity-description {
	background: #F8F9FA;
	padding: 20rpx;
	border-radius: 12rpx;
	margin-bottom: 30rpx;
	border-left: 4rpx solid #FF7D00;
}

.description-text {
	font-size: 26rpx;
	color: #333333;
	line-height: 1.6;
}

.action-buttons {
	display: flex;
	gap: 16rpx;
	flex-wrap: wrap;
}

.action-btn {
	flex: 1;
	min-width: 160rpx;
	height: 70rpx;
	border-radius: 12rpx;
	font-size: 26rpx;
	font-weight: 500;
	border: none;
	transition: all 0.2s ease;
}

.action-btn.primary {
	background: #FF7D00;
	color: #FFFFFF;
}

.action-btn.primary:active {
	background: #E66A00;
	transform: scale(0.98);
}

.action-btn.secondary {
	background: #FFFFFF;
	color: #FF7D00;
	border: 1rpx solid #FF7D00;
}

.action-btn.secondary:active {
	background: #FFF5F0;
	transform: scale(0.98);
}

/* 上传图文弹窗样式 */
.upload-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: flex-end;
	z-index: 1000;
	animation: fadeIn 0.3s ease-out;
	padding-bottom: env(safe-area-inset-bottom);
	-webkit-overflow-scrolling: touch;
}

.modal-content {
	background: #FFFFFF;
	border-radius: 24rpx 24rpx 0 0;
	width: 100%;
	max-height: 85vh;
	box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.15);
	position: relative;
	overflow: hidden;
	animation: slideUp 0.3s ease-out;
	display: flex;
	flex-direction: column;
	margin-bottom: env(safe-area-inset-bottom);
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 50rpx 40rpx 30rpx;
	border-bottom: 1rpx solid #E0E0E0;
}

.modal-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #333333;
}

.close-btn {
	width: 70rpx;
	height: 70rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.close-icon {
	font-size: 56rpx;
	color: #999999;
}

.modal-body {
	padding: 40rpx;
	flex: 1;
	overflow-y: auto;
	max-height: calc(85vh - 200rpx);
	-webkit-overflow-scrolling: touch;
}

.modal-body .form-item {
	margin-bottom: 40rpx;
}

.modal-body .form-label {
	font-size: 30rpx;
	color: #666666;
	margin-bottom: 20rpx;
	display: block;
}

.modal-body .form-input,
.modal-body .form-textarea {
	width: 100%;
	height: 90rpx;
	border: 1rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 0 24rpx;
	font-size: 30rpx;
	color: #333333;
	line-height: 1.5;
	box-sizing: border-box;
	background: #FFFFFF;
}

.modal-body .form-textarea {
	padding: 24rpx;
	min-height: 140rpx;
	height: auto;
	resize: none;
}

.attachment-area {
	display: flex;
	flex-wrap: wrap;
	gap: 24rpx;
	margin-top: 24rpx;
}

.attachment-item {
	position: relative;
	width: 140rpx;
	height: 140rpx;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.attachment-thumb {
	width: 100%;
	height: 100%;
}

.remove-btn {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	background: rgba(0, 0, 0, 0.6);
	border-radius: 50%;
	width: 44rpx;
	height: 44rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.remove-icon {
	color: #FFFFFF;
	font-size: 26rpx;
	font-weight: bold;
}

.add-attachment {
	width: 140rpx;
	height: 140rpx;
	border: 2rpx dashed #E0E0E0;
	border-radius: 12rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #F8F8F8;
}

.add-icon {
	color: #999999;
	font-size: 56rpx;
	font-weight: bold;
}

.modal-footer {
	display: flex;
	justify-content: space-between;
	padding: 40rpx;
	border-top: 1rpx solid #E0E0E0;
	background: #FFFFFF;
	flex-shrink: 0;
}

.modal-btn {
	width: 45%;
	height: 90rpx;
	border-radius: 45rpx;
	font-size: 34rpx;
	border: none;
	transition: all 0.2s ease;
	min-height: 90rpx;
}

.modal-btn.cancel {
	background: #F5F5F5;
	color: #666666;
	border: 1rpx solid #E0E0E0;
}

.modal-btn.submit {
	background: linear-gradient(135deg, #FF7D00 0%, #FF4856 100%);
	color: #FFFFFF;
}

.modal-btn.cancel:active {
	background: #D0D0D0;
	transform: scale(0.98);
}

.modal-btn.submit:active {
	background: #E66A00;
	transform: scale(0.98);
}

/* 加载状态样式 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 80rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999999;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 120rpx 0;
}

.empty-text {
	font-size: 28rpx;
	color: #999999;
}

/* 加载更多样式 */
.load-more-container {
	padding: 30rpx 0;
}

.load-more-tip {
	display: flex;
	justify-content: center;
	align-items: center;
}

.load-more-text {
	font-size: 24rpx;
	color: #999999;
}
</style> 